﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IRIS.Models;
using IRIS.Controllers;

namespace IRIS.Controllers
{
    [HandleError]
    public class EventsController : Controller
    {

        DataRepo m_Db = new DataRepo();
        #region Functions
        protected double CoordinateWorkAround(string theCoord)
        {
            // Notes: Due to short time and my lack of understanding on MSDN documentation this function was made
            // It converts a string into a double. I came a across a problem with the TryParse that wouldnt let me 
            // Parse negative number so I just delete the negative sign and Parse and add a negative when it has been
            // Converted.
            double dcoord;
            if (theCoord.Contains("-"))
            {
                var positive = theCoord.Replace("-", "");
                double.TryParse(positive, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out dcoord);
                dcoord = dcoord * -1;
            }
            else
            {
                double.TryParse(theCoord, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out dcoord);
            }
            return dcoord;
        }
        #endregion
        //
        // GET: /Events/
        public ActionResult Index()
        {

            var model = m_Db.getEventCals();
            return View(model);
            
        }
        //MasterSite rightside menu
        [ChildActionOnly]
        public ActionResult _EventMenu()
        {
            var model = m_Db.getEventCals();
            return PartialView(model);
        }
        // GET: /Events/?theDay=xx&theMonth=xx&theYear=xx
        [HandleError]
        public ActionResult Date(int? theDay, int? theMonth, int? theYear , string theMonthName)
        {
            try
            {
                if (!theMonth.HasValue && !theYear.HasValue)
                {
                    throw new Exception("Þú hefur ekki valið mánuð eða ár");
                }
                //If the day is not picked we only return the results for the month and the year. 
                if (!theDay.HasValue)
                {
                    var model = m_Db.getEventCals();
                    var range = from c in model
                                where c.EventDate.Month == theMonth && c.EventDate.Year == theYear
                                select c;
                    EventMonthViewModel eData = new EventMonthViewModel { m_event = range, m_month = theMonthName };
                    return View(eData);
                }
                else
                {
                    var model = m_Db.getEventCals();
                    var range = from c in model
                                where c.EventDate.Month == theMonth && c.EventDate.Year == theYear && c.EventDate.Day == theDay
                                select c;
                    EventMonthViewModel eData = new EventMonthViewModel { m_event = range };

                    return View(eData);
                }
            }
            catch (Exception e)
            {

                throw e;
            }
        }
        #region Create
        // GET: /Event/Create
        [Authorize(Roles = "Stjórnendur")]
        public ActionResult Create()
        {

            return View();
        }

        [Authorize(Roles = "Stjórnendur")]
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Create(FormCollection formData)
        {
            try
            {
                var newFormData = new EventCal();
                //Converting latitude
                var lat = formData["lat"];
                newFormData.lat = CoordinateWorkAround(lat);
                //Converting longitude
                var lng = formData["lng"];
                newFormData.lng = CoordinateWorkAround(lng);

                newFormData.Alive = true;
                newFormData.Description = formData["Description"];
                //Parsing from a string to a datetime datatype
                if (formData["EventDate"] == "")
                { throw new Exception("Engin dagur valinn"); }
                string strEventDate = formData["EventDate"];
                DateTime dtEventDate;
                DateTime.TryParse(strEventDate, out dtEventDate);
                newFormData.EventDate = dtEventDate;
                //Parsing the endDate the same way
                string strEndDate = formData["EventDate"];
                DateTime dtEndDate;
                DateTime.TryParse(strEventDate, out dtEndDate);
                newFormData.EndDate = dtEndDate;
                newFormData.Location = formData["Location"];
                if (formData["Title"] == "")
                { throw new Exception("Engin titill valinn"); }
                newFormData.Title = formData["Title"];

                //Submit to db
                m_Db.addEvent(newFormData);
                return RedirectToAction("Index");
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        #endregion
        #region Edit

        //Reusing the Edit function for delete, makes the code simpler as we are not deleting just modifing the value Alive
        [Authorize(Roles = "Stjórnendur")]
        [HttpGet]
        public ActionResult Edit(int? id, Boolean delete)
        {
            if (delete == true && id.HasValue)
            {
                // Only changes one value and submits the changes.
                var result = m_Db.getEventById(id);
                result.Alive = false;
                m_Db.editEvent(id.Value, result);
                return RedirectToAction("Index");
            }
            //The MSSSQL database returns us a comma seperated value
            //We convert to a string to a dot seperated value and return that with the model
            string lat = "", lng = "";
            if (id.HasValue)
            {
                var extraction = m_Db.getEventById(id.Value);
                if (extraction == null)
                    return View("NotFound");
                if (extraction.lat != null)
                {
                    lat = extraction.lat.ToString();
                    lat = lat.Replace(",", ".");
                    lng = extraction.lng.ToString();
                    lng = lng.Replace(",", ".");
                }
                var model = new EventViewModel { m_Event = extraction, m_lat = lat, m_lng = lng };
                return View(model);
            }
            return View("NotFound");
        }
        [Authorize(Roles = "Stjórnendur")]
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Edit(int id, FormCollection theFormData)
        {
            try
            {
                var newFormData = new EventCal();
                //Converting latitude
                var lat = theFormData["lat"];
                newFormData.lat = CoordinateWorkAround(lat);
                //Converting longitude
                var lng = theFormData["lng"];
                newFormData.lng = CoordinateWorkAround(lng);
                newFormData.Alive = true;
                newFormData.Description = theFormData["Description"];
                //Parsing from a string to a datetime datatype
                if (theFormData["EventDate"] == "")
                { throw new Exception("Engin dagur valinn"); }
                string strEventDate = theFormData["EventDate"];
                DateTime dtEventDate;
                DateTime.TryParse(strEventDate, out dtEventDate);
                newFormData.EventDate = dtEventDate;
                //Parsing the endDate the same way
                string strEndDate = theFormData["EventDate"];
                DateTime dtEndDate;
                DateTime.TryParse(strEventDate, out dtEndDate);
                newFormData.EndDate = dtEndDate;

                newFormData.Location = theFormData["Location"];
                if (theFormData["Title"] == "")
                { throw new Exception("Engin titill valinn"); }
                newFormData.Title = theFormData["Title"];

                m_Db.editEvent(id, newFormData);
                return RedirectToAction("Index");
            }
            catch (Exception e)
            {
                
                throw e;
            }
        }
        #endregion

        public ActionResult Details(int? id)
        {
            string lat = "", lng = "";
            if (id.HasValue)
            {
                var extraction = m_Db.getEventById(id.Value);
                if (extraction == null)
                    return View("NotFound");
                if (extraction.lat != null)
                {
                    lat = extraction.lat.ToString();
                    lat = lat.Replace(",", ".");
                    lng = extraction.lng.ToString();
                    lng = lng.Replace(",", ".");
                }
                var model = new EventViewModel { m_Event = extraction, m_lat = lat, m_lng = lng };
                return View(model);
            }
            return View("NotFound");
        }
    }
}